from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QListWidget, QMessageBox, QHBoxLayout, QInputDialog
from core.project import ProjectManagerCore
from ui.main_window import MainWindow

class ProjectManager(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("项目管理")
        self.resize(600, 400)

        layout = QVBoxLayout()
        self.project_list = QListWidget()

        btn_layout = QHBoxLayout()
        self.btn_add = QPushButton("新建项目")
        self.btn_del = QPushButton("删除项目")
        self.btn_enter = QPushButton("进入项目")
        btn_layout.addWidget(self.btn_add)
        btn_layout.addWidget(self.btn_del)
        btn_layout.addWidget(self.btn_enter)

        layout.addWidget(self.project_list)
        layout.addLayout(btn_layout)
        self.setLayout(layout)

        self.core = ProjectManagerCore()
        self.load_projects()

        self.btn_add.clicked.connect(self.add_project)
        self.btn_del.clicked.connect(self.delete_project)
        self.btn_enter.clicked.connect(self.enter_project)

    def load_projects(self):
        self.project_list.clear()
        for p in self.core.list_projects():
            self.project_list.addItem(p)

    def add_project(self):
        name, ok = QInputDialog.getText(self, "新建项目", "输入项目名称：")
        if ok and name:
            self.core.create_project(name)
            self.load_projects()

    def delete_project(self):
        current = self.project_list.currentItem()
        if current:
            self.core.delete_project(current.text())
            self.load_projects()

    def enter_project(self):
        current = self.project_list.currentItem()
        if current:
            self.main = MainWindow(project=current.text())
            self.main.show()
            self.close()
